package com.minesweeper.dialog;

import com.minesweeper.ui.GameInterface;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author skniy
 */
public class RankingList extends JDialog {

    /**
     * 构造方法
     *
     * @param level
     * @param gameInterface
     * @throws IOException
     */
    public RankingList(int level, GameInterface gameInterface) throws IOException {
        super(gameInterface);
        //加入各组件
        addItems(level);
        //设置窗口标题
        int intermediate = 1;
        int advanced = 2;
        String title = "初级排行榜";
        if (level == intermediate) {
            title = "中级排行榜";
        } else if (level == advanced) {
            title = "高级排行榜";
        }
        this.setTitle(title);
        //为了测试,不设置模态
        if (gameInterface!=null) {
            this.setModal(true);
        }
        //设置其他基本属性
        this.setSize(150, 300);
        this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        this.setLocationRelativeTo(null);
        this.setResizable(false);
        this.setVisible(true);
    }

    /**
     * 加入各组件
     *
     * @param level
     * @throws IOException
     */
    private void addItems(int level) throws IOException {
        //设置布局
        this.setLayout(new GridLayout(10, 1));
        //如果文件不存在，创建文件
        File file = new File("data/rank" + level + ".txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        //读取文件信息
        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("data/rank" + level + ".txt"), StandardCharsets.UTF_8);
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        //依次加入每条信息
        int lineLength = 10;
        for (int i = 0; i < lineLength; i++) {
            String line = bufferedReader.readLine();
            if (line == null) {
                line = "无名：999";
            } else if ("null".equals(line)) {
                line = "无名：999";
            }
            this.add(new JLabel(i + 1 + "、" + line + "s", SwingConstants.CENTER));
        }
        bufferedReader.close();
    }

}
